﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace _45ini文件读取类
{
    class Program
    {
        static void Main(string[] args)
        {
            IniFile ini = new IniFile();
            ini.ReadFile(@"E:\U\text.txt");
            string s = ini.GetString("连接信息", "主机");
            Console.WriteLine(s);
            string v = ini.GetString("设置", "音量");
            Console.WriteLine(v);
        }
    }
    class IniFile
    {
        private Dictionary<string, Dictionary<string, string>> dic = new Dictionary<string, Dictionary<string, string>>();
        public void ReadFile(string file)
        {
            string[] array = File.ReadAllLines(file);
            string mainKey = "";
            foreach (var item in array)
            {
                string line = item.Trim();
                if (line == "") continue;
                if (line.StartsWith("["))
                {
                    mainKey = line.Substring(1, line.Length - 2);
                    dic.Add(mainKey, new Dictionary<string, string>());
                }
                else if (line.Contains("="))
                {
                    string[] kv = line.Split('=');
                    dic[mainKey].Add(kv[0].TrimEnd(), kv[1].TrimStart());
                }
            }
        }
        public string GetString(string mainKey, string subKey)
        {
            return dic[mainKey][subKey];
        }
        public int GetInt(string mainKey, string subKey)
        {
            return int.Parse(GetString(mainKey, subKey));
        }
        public float GetFloat(string mainKey, string subKey)
        {
            return float.Parse(GetString(mainKey, subKey));
        }
        public bool GetBool(string mainKey, string subKey)
        {
            return bool.Parse(GetString(mainKey, subKey));
        }

    }
}
